//
//  JCNetWorkTools.swift
//  SinaWeibo_18
//
//  Created by apple on 15/10/23.
//  Copyright © 2015年 cz. All rights reserved.
//

import UIKit
import AFNetworking

enum JCNetWorkToolRequestType: String{
    case GET = "GET"
    case POST = "POST"
}

class JCNetWorkTools: NSObject {

    //  (result: [String: AnyObject]) -> ()
    class func request(type: JCNetWorkToolRequestType, url: String, var params: [String: AnyObject]?, accessToken: Bool = true, success:((result: [String: AnyObject])->()), failure: (error: NSError)->()) {
        //可以在这个地方统一添加accesstoken的参数
       //参数: APPVERSION 时间戳 渠道号 APPKEY
        if accessToken{
            if params == nil{
                params = [String: AnyObject]()
            }
            params!["access_token"] = JCUserAccount.loadUserAccount()?.access_token
            //可以在这个地方拿着params去添加基础参数

        }
        
        
        //定义请求的管理者
        let manager = AFHTTPSessionManager()
        //添加contentType
        manager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        //定义一个请求成功之后的闭包
        let successCallBack = { (dataTask: NSURLSessionDataTask, result: AnyObject) -> Void in
            if let res = (result as? [String: AnyObject]){
                //回调数据回去
                success(result: res)
            }else{
                //数据类型不对,回调错误信息
                failure(error: NSError(domain: "com.itcast.weibo", code: 10000, userInfo: ["errorMsg": "The type of result isn't [String: AnyObject]"]))
            }
        }
        
        //定义一个请求失败的闭包
        let failureCallBack = {(dataTask: NSURLSessionDataTask, error: NSError) -> Void in
            //回调数据回去
            failure(error: error)
        }
        
        //发送请求
        if type == .GET{
            //发送get请求
            manager.GET(url, parameters: params, success: successCallBack, failure: failureCallBack)
        }else{
            //发送post请求
            manager.POST(url, parameters: params, success: successCallBack, failure: failureCallBack)
        }
        
        
        
        
        
        
        
//        //发起请求
//        manager.GET(url, parameters: params, success: { (dataTask, result) -> Void in
//            //若是字典
//            if let res = (result as? [String: AnyObject]){
//                //回调数据回去
//            success(result: res)
//            }else{
//                //数据类型不对,回调错误信息
//                failure(error: NSError(domain: "com.itcast.weibo", code: 10000, userInfo: ["errorMsg": "The type of result isn't [String: AnyObject]"]))
//            }
//            
//            }) { (dataTask, error) -> Void in
//               //回调数据回去
//                failure(error: error)
//        }
    }
}
